import { Action, State, StateContext } from '@ngxs/store';
import { Injectable } from '@angular/core';
import { db } from '../../shared/common/db';
import { Cart } from './cart.actions';

export interface CartModel {
  cart?: Cart;
  list?: Cart[];
}

@State<CartModel>({
  name: 'cart',
  defaults: {
    cart: undefined,
    list: undefined,
  },
})
@Injectable({
  providedIn: 'root',
})
export class CartState {

  constructor() {
  }

  @Action(Cart.Add)
  async add({getState, patchState}: StateContext<CartModel>, {payload}: Cart.Add) {
    await db.cartList.add(payload);
    let state = getState();
    patchState({
      list: [
        ...state.list || [],
        payload,
      ],
    });
  }
}
